package bid

import (
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/go-log"
)

func saveCampaign(category string, list []advertising.CampaignInfo) {
	if len(list) == 0 {
		return
	}
	defer func() {
		if err := recover(); err != nil {
			log.Info(err)
		}
	}()
	err := app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		for _, item := range list {
			var campaign = db.AmazonCampaign{
				Category:     category,
				CampaignId:   item.CampaignId,
				CampaignName: item.Name,
			}
			var tmp []db.AmazonCampaign
			_, e = tx.Context.QueryTable(new(db.AmazonCampaign)).
				Filter("CampaignName", item.Name).
				Filter("Category", category).
				All(&tmp)
			if e != nil {
				return
			}
			if len(tmp) > 0 { // 重复
				continue
			}
			_, e = tx.Context.Insert(&campaign)
			if e != nil {
				log.Info(e)
				return
			}
		}

		return
	})
	if err != nil {
		log.Info(err)
		return
	}

}

func saveKeywords(category string, kw ...advertising.KeywordInfo) {
	err := app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		for _, item := range kw {
			var list []db.AmazonKeyword
			_, e = tx.Context.QueryTable(new(db.AmazonKeyword)).
				Filter("Category", category).
				Filter("KeywordId", item.KeywordId).All(&list)
			if e != nil {
				return
			}
			if len(list) > 0 {
				tmp := list[0]
				tmp.State = item.State
				tmp.Bid = item.Bid
				//log.Info("update amazon_keyword: %s", tmp.KeywordId)
				_, e = tx.Context.Update(&tmp)
				if e != nil {
					log.Info(e)
					return
				}
			} else {
				//log.Info("save amazon_keyword: %s", item.KeywordId)
				var tmp db.AmazonKeyword
				tmp.Category = category
				tmp.KeywordId = item.KeywordId
				tmp.KeywordText = item.KeywordText
				tmp.MatchType = item.MatchType
				tmp.CampaignId = item.CampaignId
				tmp.AdGroupId = item.AdGroupId
				tmp.State = item.State
				tmp.Bid = item.Bid
				_, e = tx.Context.Insert(&tmp)
				if e != nil {
					log.Info(e)
					return
				}
			}
		}
		return
	})
	if err != nil {
		log.Info(err)
	}
}
